package secondPart;

public class DealLockThreadDemo {

    public static void main(String[] args) {
        DealThread dealThread1 = new DealThread();
        dealThread1.setFlag("a");
//        DealThread dealThread2 = new DealThread();
        Thread thread1 = new Thread(dealThread1);
        thread1.start();
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        dealThread1.setFlag("b");
        Thread thread2 = new Thread(dealThread1);
        thread2.start();
    }
}

class DealThread implements Runnable {
    public String username;
    public Object lock1 = new Object();
    public Object lock2 = new Object();

    public void setFlag(String username) {
        this.username = username;
    }

    @Override
    public void run() {
        if (username.equals("a")) {
            synchronized (lock1) {
                try {
                    System.out.println("username = " + username);
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (lock2) {
                    System.out.println("按照lock1->lock2的顺序执行代码");
                }
            }
        }

        if (username.equals("b")) {
            synchronized (lock2) {
                try {
                    System.out.println("username = " + username);
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (lock1) {
                    System.out.println("按照lock2->lock1的顺序执行代码");
                }
            }
        }
    }
}

//        Found one Java-level deadlock:
//        =============================
//        "Thread-1":
//        waiting to lock monitor 0x000000001c0cf678 (object 0x000000076b88f340, a java.lang.Object),
//        which is held by "Thread-0"
//        "Thread-0":
//        waiting to lock monitor 0x000000001c0cb528 (object 0x000000076b88f350, a java.lang.Object),
//        which is held by "Thread-1"
//
//        Java stack information for the threads listed above:
//        ===================================================
//        "Thread-1":
//        at secondPart.DealThread.run(DealLockThreadDemo.java:56)
//        - waiting to lock <0x000000076b88f340> (a java.lang.Object)
//        - locked <0x000000076b88f350> (a java.lang.Object)
//        at java.lang.Thread.run(Thread.java:748)
//        "Thread-0":
//        at secondPart.DealThread.run(DealLockThreadDemo.java:42)
//        - waiting to lock <0x000000076b88f350> (a java.lang.Object)
//        - locked <0x000000076b88f340> (a java.lang.Object)
//        at java.lang.Thread.run(Thread.java:748)
//
//        Found 1 deadlock.
